<?php
class Pageclass extends CI_Model{
function page($sql,$page='',$pageSize = 20, $indexLength = 5) {//$sql,原始sql语句，$pageSize,每页显示记录数，$indexLength，显示页码 
	global $pageIndexBar;//$db,mysql new来的,$pageIndexBar直接当前页面用的导航条
	//得到当前的URL值 
	$curUrl = $_SERVER['QUERY_STRING']; 
	if($curUrl == '') { 
	  $curUrl = "?page="; 
	} else { 
	  $curUrl = preg_replace("/&?page=\d+/", '', $curUrl); 
	  $curUrl = "?" . $curUrl . "&page="; 
	} 
	//查得总记录数 
	$rs = $this->db->query($sql);//CI中的DB类 
	$totalNum = $rs->num_rows(); 
	//取得最大页数 
	$maxPage = ceil($totalNum / $pageSize); 
	$maxPage = $maxPage < 1 ? 1 : $maxPage; 
	//取得当前页码 
	$curPage = $page; 
	$curPage = ($curPage == '' || $curPage < 1) ? 1 : $curPage; 
	if($curPage > $maxPage) { 
	  $curPage = $maxPage; 
	} 
	//分页导航 
	if($maxPage <= $indexLength) { 
	  $firstNum = 1; 
	  $lastNum = $maxPage; 
	} else { 
	  $offset = floor($indexLength / 2); 
	  if(($curPage - $offset) <= 1) { 
	   $firstNum = 1; 
	  } elseif(($curPage + $offset) > $maxPage) { 
	   $firstNum = $maxPage - $indexLength + 1; 
	  } else { 
	   $firstNum = $curPage - $offset; 
	  } 
	  $lastNum = $firstNum + $indexLength - 1; 
	} 
	$pageIndex='';
	for($i = $firstNum; $i <= $lastNum; $i++) { 
	  if($curPage == $i) { 
	   $pageIndex .= "<a class='number current' href='javascript:void(0)'>".$i."</a>"; 
	  } else { 
	   $pageIndex .= "<a class='number' href='" . $curUrl . $i . "'>" . $i . "</a>  "; 
	  } 
	} 
	$pageIndexTotal = "共<span class='fred'>$maxPage</span>页  <span class='fred'>$totalNum</span>条记录  "; 
	$pageIndexNav = $curPage > 1 ? "<a href='" . $curUrl . "1'>&laquo; 首页</a>  <a href='" . $curUrl . ($curPage - 1) . "'>&laquo; 上一页</a>  " : "首页  上一页  "; 
	$pageIndexEnd = $curPage < $maxPage ? "<a href='" . $curUrl . ($curPage + 1) . "'>下一页 &raquo;</a>  <a href='" . $curUrl . $maxPage . "'>末页 &raquo;</a>" : "下一页  末页"; 
	if($maxPage == 1) { 
	  $pageIndexBar = $pageIndexTotal; 
	} else { 
	  $pageIndexBar = $pageIndexTotal . $pageIndexNav . $pageIndex . $pageIndexEnd; 
	} 

	//数据库分页开始 
	$sql = $sql . " LIMIT " . ($curPage - 1) * $pageSize . "," . $pageSize;
	return $sql;//返回sql
	} 

}
//$page = new PageClass();
?>